//
//  Message_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/10.
//
//

import UIKit
import RickonCore
import UtilCore
import MJRefresh
import EmptyDataView
import URLNavigator
import BrandonCore

class Message_Vc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var Message_TableView: UITableView!                  //消息表
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var message_VM:GetMessageListVm?
    
    let hearder1 = MJRefreshNormalHeader()                              //商品顶部刷新
    
    let footer1 = MJRefreshAutoNormalFooter()                           //商品底部刷新
    
    var btnArr = [UIButton]()                                           //按钮数组
    
    var isrefresh = true                                                //是否刷新
    
    var isSystem  = false
    
    var message_Arr:[RowsModel]?{
        didSet{
            self.Message_TableView.reloadData()
        }
        
    }
    var type = 2
    
    var messageRedVM:MessageRedVM?
    
    var messageIndex:Int?{
        didSet{
            if messageIndex == 0{
                type = 2
            }else if messageIndex == 1{
                type = 1
            }else{
                type = 0
            }
        }
    }
    
    /****************************Storyboard 绑定方法区域****************************/

    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let _ = AppData.loginedUser{
            self.message_VM?.message_Type.onNext("\(type)")
            self.message_VM?.messageType = "\(type)"
        }else{
            AuditInfoView.showByView(supView: self.view)
//            self.Message_TableView.isScrollEnabled = false
        }
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        
        // 上拉刷新
        hearder1.setRefreshingTarget(self, refreshingAction: #selector(Message_Vc.headerRefresh))
        self.Message_TableView.mj_header = hearder1
        self.Message_TableView.showsVerticalScrollIndicator = false
        
        // 下拉加载更多
        footer1.setRefreshingTarget(self, refreshingAction: #selector(Message_Vc.footerRefresh))
        footer1.isAutomaticallyHidden = true
        self.Message_TableView.mj_footer = footer1
        
        self.Message_TableView.dzn_tv_emptyDataSource = self
        self.Message_TableView.dzn_tv_emptyDelegate = self
        self.Message_TableView.backgroundView = UIView()
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setupMessageTableView()
    }
    func setupMessageTableView(){
        
        self.Message_TableView.delegate = self
        self.Message_TableView.dataSource = self
        self.Message_TableView.estimatedRowHeight = 200
        self.Message_TableView.rowHeight = UITableViewAutomaticDimension

    }
    func headerRefresh(){
        self.hearder1.endRefreshing()
        
    }
    func footerRefresh(){
        self.footer1.endRefreshing()
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        self.message_VM = GetMessageListVm(
            input:(
                refreshTriger:  rx.sentMessage(#selector(Message_Vc.headerRefresh)).map { _ in () },
                loadMoreTriger: rx.sentMessage(#selector(Message_Vc.footerRefresh)).map { _ in () }
            )
        )
        self.message_VM?
            .backDate
            .asObservable()
            .do(onNext: {[unowned self] _ in
                
                self.errorPageView.isHidden = true
                
            })
            .skip(1)
            .subscribe(onNext:{ result in
                
                self.showEmptyView = true
                self.message_Arr = result
                
            }).addDisposableTo(disposeBag)
        
        //是否还有下一页
        self.message_VM?.hasNextPage.asDriver().asObservable().subscribe(onNext:{ hasNextPage in
            if !hasNextPage{
                self.footer1.endRefreshingWithNoMoreData()
            }else{
                self.footer1.resetNoMoreData()
            }
        }).addDisposableTo(disposeBag)
        
        self.message_VM?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        //绑定错误
        self.message_VM?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        //-----
        //错误处理
        self.message_VM?.refresherror.asObserver().bindTo(self.rx_showerrorpage).addDisposableTo(disposeBag)
        
        self.errorPageView.reloadSubject.bindTo(self.message_VM!.reloadTrigger).addDisposableTo(disposeBag)
        //-----
        
        //-----
        //标记已读
        self.messageRedVM = MessageRedVM()
        
        self.messageRedVM?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
    }
}
extension Message_Vc:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        guard let modelArr = self.message_Arr else { return 0 }
        return modelArr.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! Message_Header_TableViewCell
        cell.time_Label.text = self.message_Arr?[section].mtime
        
        guard #available(iOS 9.0, *) else {
            cell.setNeedsUpdateConstraints()
            cell.updateConstraintsIfNeeded()
            return cell
        }
        return cell
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.message_Arr?[indexPath.section]

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Message_TableViewCell

        let systemCell = tableView.dequeueReusableCell(withIdentifier: "system") as! System_Message_TableViewCell
        

        if self.type == 0{
            
            systemCell.layer.cornerRadius = 8
            systemCell.layer.masksToBounds = true
            systemCell.item = model
            guard #available(iOS 9.0, *) else {
                systemCell.setNeedsUpdateConstraints()
                systemCell.updateConstraintsIfNeeded()
                return systemCell
            }
            return systemCell
        }else{
            
            cell.layer.cornerRadius = 8
            cell.layer.masksToBounds = true
            cell.item = model
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let modelArr = self.message_Arr{
            if modelArr.count >= indexPath.section{
                let model = modelArr[indexPath.section]
                if model.readabled == "0"{
                    self.messageRedVM?.messageRed.onNext("\(model.mid)")
                }
                _ = Navigator.open(model.murl)
            }
        }
    }
}
extension Message_Vc:EmptyDataSource{
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString? {
        return Theme.getEmptyDesc("亲,暂时没有消息哦~")
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage? {
        return UIImage.init(named: "Listkong_Image", in: SansaCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
       return UIColor.white
    }
    
    
}
